import dwUser from '@/models/dwUser';
import { setUserCookie } from '@/utils/Auth/auth';
import dayjs from 'dayjs';
import md5 from 'js-md5';
import { ObjectId } from 'mongodb';
import { addLogs } from '../logs';

interface ParamsType {
  token: string;
  uuid: string;
  roles: Roles;
  nickname: string;
  avatar: string;
}

interface Roles {
  menu: any[];
}

// 配置用户
export const dingUser = async (params: ParamsType) => {
  const { nickname, uuid, avatar, token } = params;
  const timeData = {
    updateTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    gmtCreated: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  };
  const res = await dwUser.findOne({ userName: nickname });
  console.log(!res);
  if (res && res.isDelete === 0) {
    addLogs(4, 11, nickname, [], res._id);
    const tokenOld: string = await setUserCookie({ personId: String(res._id), personName: nickname, role: res.role });
    if (res.uuid) {
      return {
        isError: false,
        data: { ...res, token: tokenOld, personId: res._id },
      };
    }
    const { _id } = res;
    await dwUser.update({ nickname, uuid, avatar, dingToken: token }, { _id: new ObjectId(_id) });
    return {
      isError: false,
      data: { ...res, nickname, uuid, avatar, dingToken: token, token: tokenOld, personId: res._id },
    };
  }
  if (!res) {
    const addUser = {
      userName: nickname,
      name: nickname,
      role: '64feec8ae6de3ece9c58b582',
      dingToken: token,
      password: md5('123456'),
      uuid,
      avatar,
      isDelete: 0,
      ...timeData,
    };
    const save = await dwUser.insert(addUser);
    const tokenOld: string = await setUserCookie({ personId: String(save.insertedId), personName: nickname });
    addLogs(4, 11, nickname, [], save.insertedId);
    return {
      isError: false,
      data: { ...addUser, token: tokenOld, personId: save.insertedId },
    };
  }
  return {
    isError: true,
    message: '用户不存在',
  };
};
